package com.xianggu.spring;

import com.xianggu.annotation.FeignClient;
import com.xianggu.proxy.InterfaceRpcProxy;
import com.xianggu.spring.expand.BeanLoadingExtension;

import java.beans.Introspector;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class MyExtension implements BeanLoadingExtension {
    /**
     * 为Feign客户端创建代理对象
     *
     * @param beanName
     * @param beanDefinition
     * @return
     */
    @Override
    public Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class<?> beanClass = beanDefinition.getBeanClass();
        if (beanClass.isAnnotationPresent(FeignClient.class)) {
            // 先从容器中找，没有再生成代理对象
            return InterfaceRpcProxy.getProxy(beanClass);
        }
        return null;
    }

    @Override
    public boolean isBean(Class<?> clazz) {
        if (clazz.isAnnotationPresent(FeignClient.class)) {
            return true;
        }
        return false;
    }

    @Override
    public String getBeanName(Class<?> clazz) {
        if (clazz.isAnnotationPresent(FeignClient.class)) {
            FeignClient annotation = clazz.getAnnotation(FeignClient.class);
            if(annotation.beanName() != null && !annotation.beanName().isEmpty()) {
                return annotation.beanName();
            }
        }
        return Introspector.decapitalize(clazz.getSimpleName());
    }
}